'use strict';

/**
 * @ngdoc function
 * @name sfhtHaitaoCmsApp.controller:MainCtrl
 * @description
 * # MainCtrl
 * Controller of the sfhtHaitaoCmsApp
 */
angular.module('sfhtHaitaoCmsApp')
    .controller('SidebarCtrl', function($scope, $modal, $log, $location, $injector, CONST_WEB_LOGIN_LINK, store) {
        $('#sidebar').dynamic({
            customScroll: {
                color: '#fff', //color of custom scroll
                rscolor: '#95A5A6', //color of right sidebar
                size: '3px', //size in pixels
                opacity: '1', //opacity
                alwaysVisible: false //disable hide in
            },
            header: {
                fixed: true //fixed header
            },
            breadcrumbs: {
                auto: true, //auto populate breadcrumbs via js if is false you need to provide own markup see for example.
                homeicon: 'im-home6' //home icon 
            },
            sidebar: {
                fixed: true, //fixed sidebar
                rememberToggle: true, //remember if sidebar is hided
                offCanvas: false //make sidebar offcanvas in tablet and small screens
            },
            rightSidebar: {
                fixed: true, //fixed sidebar
                rememberToggle: true //remember if sidebar is hided
            },
            sideNav: {
                toggleMode: true, //close previous open submenu before expand new
                showArrows: true, //show arrow to indicate sub
                sideNavArrowIcon: 'l-arrows-right', //arrow icon for navigation
                subOpenSpeed: 200, //animation speed for open subs
                subCloseSpeed: 300, //animation speed for close subs
                animationEasing: 'linear', //animation easing
                absoluteUrl: false, //put true if use absolute path links. example http://www.host.com/dashboard instead of /dashboard
                subDir: '' //if you put template in sub dir you need to fill here. example '/html'
            },
            panels: {
                refreshIcon: 'fa fa-circle-o', //refresh icon for panels
                toggleIcon: 'fa fa-angle-up', //toggle icon for panels
                collapseIcon: 'fa fa-angle-down', //colapse icon for panels
                closeIcon: 'fa fa-times', //close icon
                showControlsOnHover: false, //Show controls only on hover.
                loadingEffect: 'rotateplane', //loading effect for panels. bounce, none, rotateplane, stretch, orbit, roundBounce, win8, win8_linear, ios, facebook, rotation, pulse.
                loaderColor: '#616469',
                rememberSortablePosition: true //remember panel position
            },
            accordion: {
                toggleIcon: 'l-arrows-minus s16', //toggle icon for accrodion
                collapseIcon: 'l-arrows-plus s16' //collapse icon for accrodion
            },
            tables: {
                responsive: true, //make tables resposnive
                customscroll: true //ativate custom scroll for responsive tables
            },
            alerts: {
                animation: true, //animation effect toggle
                closeEffect: 'bounceOutDown' //close effect for alerts see http://daneden.github.io/animate.css/
            },
            dropdownMenu: {
                animation: true, //animation effect for dropdown
                openEffect: 'fadeIn', //open effect for menu see http://daneden.github.io/animate.css/
            }
        });


        $scope.specialPages = null;
        $scope.profile = null;
        var topicService = $injector.get("TopicService");
        var pageService = $injector.get("PageService");
        var commonBizService = $injector.get("CommonBiz");
        var userService = $injector.get("UserService");

        $scope.slidebarInit = function() {
            topicService.getSpecialPageList()
                .then(function(data) {
                    $scope.specialPages = data.value;
                });
            if (store.get("profile")) {
                $scope.profile = store.get("profile");
            } else {
                commonBizService.getUserProfile()
                    .then(function(data) {
                        store.set("profile", data);
                        $scope.profile = data;
                    }, function(data) {
                        alert(data);
                    })
            }
        };

        $scope.changePassword = function(){
            var modal = $modal.open({
                animation: true,
                templateUrl: 'user.changepassword.html',
                controller: 'ModalChangePasswordCtrl',
                resolve: {
                    
                }
            });
        }
        //添加页面
        $scope.pageAdd = function(pageid) {
            pageService.getResourceConfigs()
                .then(function(data) {
                    var modal = $modal.open({
                        animation: true,
                        templateUrl: 'page.property.edit.html',
                        controller: 'ModalCreatePageCtrl',
                        resolve: {
                            page: function() {
                                return _.findWhere($scope.pages, {
                                    id: pageid
                                });
                            },
                            headers: function() {
                                var headers = [];
                                _.each(data.value, function(value, key, list) {
                                    headers.push({
                                        name: value.name,
                                        description: value.description,
                                        resourceType: value.resourceType
                                    });
                                });
                                return headers;
                            }
                        }
                    });
                    modal.result.then(function(pageId) {
                        $location.path("/page/edit/" + pageId);
                    }, function(data) {
                        window.history.back();
                    });
                }, function(data) {
                    alert("获取可用头部失败:" + data);
                });
        };

        //关联新页面
        $scope.relateNewPage = function() {
            var pageService = $injector.get("PageService");
            pageService.getResourceConfigs()
                .then(function(data) {
                    var modal = $modal.open({
                        animation: true,
                        templateUrl: 'page.property.edit.html',
                        controller: 'ModalCreateNewTopicCtrl',
                        resolve: {
                            headers: function() {
                                var headers = [];
                                _.each(data.value, function(value, key, list) {
                                    headers.push({
                                        name: value.name,
                                        description: value.description,
                                        resourceType: value.resourceType
                                    });
                                });
                                return headers;
                            }
                        }
                    });
                    modal.result.then(function(pageId) {
                        $location.path("/page/edit/" + pageId);
                    }, function() {
                        window.history.back();
                    });
                });
        };
        /**
         * 退出登入
         * @return {[type]} [description]
         */
        $scope.logout = function() {
            userService.logout()
                .then(function(data) {
                    store.remove('csrfToken');
                    store.remove("userId");
                    store.remove('profile');
                    window.location.href = CONST_WEB_LOGIN_LINK;
                }, function(data) {
                    alert(data);
                })
        };
        /**
         * 退出登入
         * @return {[type]} [description]
         */
        $scope.uploadfile = function() {
            var modal = $modal.open({
                animation: true,
                templateUrl: 'util.fileupload.html',
                controller: 'UtilUploadFileCtrl',
            });
        };
        $scope.toolsMap = function() {
            var modal = $modal.open({
                animation: true,
                templateUrl: 'tools.map.html',
                controller: 'ToolsMapCtrl'
            });
        };

        //展开收缩侧边栏

        $scope.toggleSidebar = function() {
            $scope.showSidebar = !$scope.showSidebar;
            $('#page-wrapper').toggleClass('active');
        };

        $scope.goback = function() {
            window.history.back();
        };

        $scope.forward = function() {
            window.history.forward();
        };
    })
    /**
     * todo refactory,see page property js
     * @param  {[type]} $scope         [description]
     * @param  {[type]} $modalInstance [description]
     * @param  {[type]} PageService    [description]
     * @param  {[type]} TopicService   [description]
     * @param  {Object} headers)       {                                             $scope.page [description]
     * @param  {[type]} options.value: 1                  [description]
     * @param  {[type]} options.name:  'H5'               [description]
     * @param  {[type]} options.icon:  'images/phone.png' [description]
     * @param  {[type]} {                                                 value: 2,                              name: 'APP',      icon: 'images/app.png'    }];    $scope.headers [description]
     * @return {[type]}                [description]
     */
    .controller('ModalCreateNewTopicCtrl', function($scope, $modalInstance, $injector, PC_HEADER_RESOURCE_TYPE, H5_HEADER_RESOURCE_TYPE, headers, Uploader) {
        $scope.isTopic = true;
        $scope.topic = {};
        $scope.topic.status = 1;
        $scope.page = {};
        if (!$scope.page.pageConfig) {
            $scope.page.pageConfig = {};
        }
        $scope.isEdit = false;
        $scope.title = "新增页面";
        $scope.pageTypes = [{
            value: 0,
            name: 'PC',
            icon: 'images/laptop.png'
        }, {
            value: 1,
            name: 'H5',
            icon: 'images/phone.png'
                // }, {
                // value: 2,
                // name: 'APP',
                // icon: 'images/app.png'
        }];
        $scope.headers = headers;
        // if (!$scope.isEdit) {
        //     $scope.page.pageType = $scope.pageTypes[0].value;
        //     $scope.page.header = $scope.headers[0].value;
        // }
        if (!$scope.page.pageConfig.backgroundColor) {
            $scope.page.pageConfig.backgroundColor = "#F5F5F5";
        }
        var pageService = $injector.get("PageService");
        var topicService = $injector.get("TopicService");
        $scope.page.isShareIconCompleted = false;
        $scope.page.isBackgroundUrlCompleted = false;
        $scope.changeFile = function(imgName) {
            Uploader.uploadFile($scope, imgName);
        };
        var pageId;

        //日历
        $scope.initTime = function() {
            if ($scope.isTopic) {
                $('.datetimepicker').datetimepicker({
                    format: 'YYYY-MM-DD HH:mm'
                })
            }
        };

        $scope.dateChange = function(topic, index) {
            if (index == 1) {
                topic.starttime = $('.datetimepicker1').val();
            }
            if (index == 2) {
                topic.endtime = $('.datetimepicker2').val();
            }
        };

        /**
         * 新建页面以及对应的专题
         * @param  
         * @return {array}
         */
        $scope.save = function(topic) {
            if ($scope.isTopic) {
                if (topic.starttime) {
                    $scope.topic.starttime = new Date(topic.starttime).getTime();
                }
                if (topic.endtime) {
                    $scope.topic.endtime = new Date(topic.endtime).getTime();
                }
            }
            pageService.createPage($scope.page)
                .then(function(data) {
                    pageId = data.value;
                    topicService.saveTopic(pageId, $scope.topic.starttime, $scope.topic.endtime, $scope.topic.status)
                        .then(function(data) {
                            $modalInstance.close(pageId);
                        }, function(data) {
                            alert(data);
                        });
                }, function(data) {
                    alert("新增专题失败:" + data);
                })
        };
        $scope.cancel = function() {
            $modalInstance.dismiss('cancel');
        };
        $scope.findHeader = function(page) {
            if (page == 0) {
                $scope.headers = headers;
                $scope.headers = _.filter($scope.headers, function(data) {
                        return data.resourceType == PC_HEADER_RESOURCE_TYPE
                    })
                    if (!$scope.isEdit) {
                        $scope.page.header = $scope.headers[0].name;
                    }
            } else {
                $scope.headers = headers;
                $scope.headers = _.filter($scope.headers, function(data) {
                        return data.resourceType == H5_HEADER_RESOURCE_TYPE
                    })
                    if (!$scope.isEdit) {
                        $scope.page.header = $scope.headers[0].name;
                    }
            }
        };
    }).controller('UtilUploadFileCtrl', function($scope, $modal, Uploader, $modalInstance) {
        $scope.uploadfile = {
            isCompleted: false,
            filename: null
        };

        $scope.changeFile = function(uploadfile) {
            Uploader.uploadFile($scope, uploadfile);
        };
        $scope.cancel = function() {
            $modalInstance.dismiss('cancel');
        };
    })
    .controller('ToolsMapCtrl', function($scope, $modal, Uploader, $modalInstance, store) {
        $scope.iframeHeight = $(window).height() - 130;
        $scope.uploadfile = {
            isCompleted: false,
            filename: null
        };

        $scope.changeFile = function(uploadfile) {
            Uploader.uploadFile($scope, uploadfile);
        };
        $scope.cancel = function() {
            $modalInstance.dismiss('cancel');
        };
    })
    .controller('ModalChangePasswordCtrl', function($scope, $modal, $injector, $modalInstance, CONST_PASSWORD_SLOT, store){
        var userService = $injector.get("UserService");
        $scope.accountId =  store.get("profile").telephone;
        if(!$scope.accountId){
            window.location.href = CONST_WEB_LOGIN_LINK;
        }
        $scope.changePassword = function(){
           if(!($scope.newPassword && $scope.newPassword == $scope.confirmPassword)){
                alert("新密码和确认密码要一致，并且不能为空！");
                return ;
           }
           if(!$scope.oldPassword){
                alert("旧密码不能为空！");
                return ;
           }
           var params = {
            oldpwd:faultylabs.MD5($scope.oldPassword + CONST_PASSWORD_SLOT).toLowerCase(),
            newpwd:faultylabs.MD5($scope.newPassword + CONST_PASSWORD_SLOT).toLowerCase(),
            accountId:$scope.accountId
           };
           userService.changePassword(params).then(function(data){
              if(data.value){
                $modalInstance.close();
              }else{
                alert("修改失败！");
              }
              
           }, function(data){
                alert(data);
           });
        }
        $scope.cancel = function() {
            $modalInstance.dismiss('cancel');
        };
    });

